package xyz.xpman.prisonerfitness.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import java.util.function.Function;

import xyz.xpman.prisonerfitness.R;
import xyz.xpman.prisonerfitness.activity.base.BaseActivity;
import xyz.xpman.prisonerfitness.entity.User;
import xyz.xpman.prisonerfitness.service.GroupRestTimeUtil;
import xyz.xpman.prisonerfitness.service.UserService;
import xyz.xpman.prisonerfitness.util.AppUtil;
import xyz.xpman.prisonerfitness.util.ToastUtil;

public class SettingActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        SettingsFragment.context = this;

        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings, new SettingsFragment())
                    .commit();
        }

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

    }



    public static class SettingsFragment extends PreferenceFragmentCompat {
        @SuppressLint("StaticFieldLeak")
        public static Context context;
        private Preference userPreference = null;
        private Preference restTimePreference = null;

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.setting_preferences, rootKey);

            userPreference = findPreference(getString(R.string.user_setting_key));
            restTimePreference = findPreference(getString(R.string.group_rest_time_key));


            // 未登录则跳转登录，否则进入用户设置
            userPreference.setOnPreferenceClickListener(view-> {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    processUser();
                }
                return true;
            });



            // 组休息时间
            restTimePreference.setOnPreferenceClickListener(view-> {
                Intent intent = new Intent(context, GroupRestTimeSettingActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                return true;
            });

            // 去评分
            clickEvent(getString(R.string.go_to_rate_key), view-> {
                // TODO: 2021/5/26 自动跳转到应用市应用评分页面
                ToastUtil.showText(context, "暂未适配所有应用商店");
                return true;
            });


            // 检查更新
            clickEvent(getString(R.string.check_update_key), view-> {
                String versionInfo = AppUtil.getVersionInfo();
                String format = String.format("当前app(%s)已是最新版本", versionInfo);
                ToastUtil.showText(context, format);
                return true;
            });
        }


        @RequiresApi(api = Build.VERSION_CODES.N)
        private void clickEvent(@NonNull CharSequence key, Function<Preference, Boolean> func) {
            Preference preference = findPreference(key);

            if (null != preference) {
                preference.setOnPreferenceClickListener(func::apply);
                return;
            }

            final String format = "Preference for key(%s) is null.";
            Log.w("[SettingsFragment]", String.format(format, key));
        }



        @RequiresApi(api = Build.VERSION_CODES.O)
        private void processUser() {
            if (UserService.ME.isUserLoggedIn()) {
                startActivity(new Intent(context, UserIndexActivity.class));
            } else {
                startActivity(new Intent(context, LoginActivity.class));
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        private void processUserInfo() {
            User user = UserService.ME.getCurrentUser();

            userPreference.setTitle(user.getUsername());
            userPreference.setSummary("已同步");
        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        private void processUserLogout() {
            userPreference.setTitle("未登录");
            userPreference.setSummary("登录后可保存数据到云账号");
        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onResume() {
            super.onResume();
            Log.i("SettingsFragment", "resume....");

            restTimePreference.setSummary(String.valueOf(GroupRestTimeUtil.get()));

            if (UserService.ME.isUserLoggedIn()) {
                processUserInfo();
            } else {
                processUserLogout();
            }
        }
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return processMenuItemForBack(item);
    }


}
